package com.ht.WeNas.config.data;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Configuration
public class CacheConfig {
    public static class MyCacheManager implements CacheManager {
        private final ConcurrentHashMap<String, Cache> caches = new ConcurrentHashMap<>();

        public MyCacheManager() {
            // 初始化sys:开头的缓存和普通缓存
            for (var value : CacheNameEnum.values()) {
                if (value.getSuffix().startsWith(":sys")) {
                    this.caches.put(value.getName(), buildCache(1));
                } else {
                    this.caches.put(value.getName(), buildCache(1000));
                }
            }
        }

        private Cache buildCache(long duration) {
            return new CaffeineCache("cache",
                    Caffeine.newBuilder()
                            .expireAfterWrite(duration, TimeUnit.SECONDS)
                            .build());
        }

        @Override
        public Cache getCache(String name) {
            return caches.get(name);
        }

        @Override
        public Collection<String> getCacheNames() {
            return caches.keySet();
        }
    }

    @Bean
    @Primary
    public CacheManager cacheManager() {
        return new MyCacheManager();
    }
}
